<?php

class SaleModel extends Model
{
    //退款
    public function refund($sale_id, $site_id, $thnum)
    {
        $sale = $this->where(array('id' => $sale_id, 'site_id' => $site_id, 'pay_status' => 1))->find();
        if (!$sale) {
            return false;
        }
        if ($sale['num'] < $thnum) {
            return false;
        } else {
            $udata['num'] = $sale['num'] - $thnum;
            if($udata['num'] < 0){
                return false;
            }else{
                if($udata['num'] > 0){
                    //部分退款
                    $udata['pay_status'] = 2;
                }else{
                    //全部退款
                    $udata['pay_status'] = 3;
                }
                $udata['total'] = $sale['total'] - $sale['price']*$thnum;
                $udata['thnum'] = $thnum;
                $ret = $this->where(array('id' => $sale_id)) -> data($udata) -> save();
                if($ret !== false){
                    //正确之后退款到会员账户
                    $maldb = D('Member_account_log');
                    $ordernumber = M('Order') -> where(array('id' => $sale['order_id'])) -> getField('ordernumber');
                    $maldb -> change($sale['thnum']*$sale['price'], $sale['member_id'], '订单：'.$ordernumber.'退款');
                    return true;
                }else{
                    return false;
                }
            }
		}
        return true;
    }
}